﻿function groupScheduleViewModel(parent) {
    var self = this;

    if (parent != null)
        extend(this, parent);

    //######################### Public properties ####################################
    self.addLessonCardModel = {
        tutorial: ko.observable(),
        tutorialType: ko.observable(),
        times: ko.observableArray([]),
        lecturers: ko.observableArray([]),
        daysOfWeek: ko.observableArray([]),
        auditorium: ko.observable(),
        lecturer: ko.observable(),
        time: ko.observable(),
        isupdate: false,

        init: function () {
            this.tutorial(undefined);
            this.tutorialType(undefined);
            this.times([]);
            this.lecturers([]);
            this.daysOfWeek([]);
            this.auditorium(undefined);
            this.lecturer(undefined);
            this.time(undefined);
            this.isupdate = false;
        },

        save: function () {
            var times = [];

            $.each(self.addLessonCardModel.times(), function(index, item){
                times.push({"Id": item});
            });

            var actionName;

            if(!self.addLessonCardModel.isupdate)
                actionName = "schedule/add";
            else
                actionName = "schedule/update";

            self.sendData({
                address: actionName,
                params: {
                    'tutorial.Id': self.addLessonCardModel.tutorial(),
                    'tutorialType.Id': self.addLessonCardModel.tutorialType(),
                    'group.Id': self.currentGroup(),
                    'times': times,
                    'time.Id': self.addLessonCardModel.time,
                    'daysOfWeek': self.addLessonCardModel.daysOfWeek(),
                    'auditorium': self.addLessonCardModel.auditorium(),
                    'lecturer': self.addLessonCardModel.lecturer(),
                    'id': self.selectedScheduleCard(),
                },
                onsuccess: function (data) {
                    $("option:selected").prop("selected", false);

                    $("#lessonCardSuccessMessage").show();

                    setTimeout(function() {
                        $("#lessonCardSuccessMessage").hide();
                    }, 3000);

                    self.loadData({
                        address: "schedule/getforgroup",
                        params: {'groupId': self.currentGroup()},
                        onsuccess: function (data) {
                            self.applySchedule(data);
                        },
                        onerror: function (x,h,r) {
                        }
                    });

                    self.addLessonCardModel.init();
                }, 
                onerror: function(error) {
                    self.showError("Cохранение неудалось!");
                }
            });            
        },

        saveAndClose: function() {
            self.addLessonCardModel.save();
            self.addLessonCardModel.window.modal("hide");
        },
    };    

    self.currentFaculty = ko.observable(11);
    self.currentCourse = ko.observable(1);
    self.currentGroup = ko.observable();
    self.schedule = ko.observableArray([]);
    //######################### End public properties #################################

    //######################### Private methods #######################################
    function LoadGroups() {
        self.loadData({
            address: "group/get/",
            obj: self.groups,
            params: {
                facultyid: self.currentFaculty(),
                courseid: self.currentCourse(),
            },
            onbefore: function() {
                self.groups([]);
            },
            onsuccess: function () {
            }
        });
    }

    self.applySchedule = function(data) {
        var days = [["", "", "", "", "", "", "", "", "", ""],
            ["", "", "", "", "", "", "", "", "", ""],
            ["", "", "", "", "", "", "", "", "", ""],
            ["", "", "", "", "", "", "", "", "", ""],
            ["", "", "", "", "", "", "", "", "", ""],
            ["", "", "", "", "", "", "", "", "", ""]];
        $.each(data, function(index, item) {

            days[item.DayOfWeek - 1][item.Period.Id - 1] = {
                Id: item.Id,
                TutorialName: item.Tutorial.Name,
                TutorialTypeName: item.TutorialType.Name,
                BuildingName: item.Auditorium.Building.Name,
                AuditoriumNum: item.Auditorium.Number,
                Lecturer: item.Lecturer.Lastname + " " + item.Lecturer.Firstname + " " + item.Lecturer.Middlename
            };
        });

        self.schedule(days);
    };

    function unselectSchedule() {
        self.selectedScheduleCard(undefined);
        
        self.addLessonCardModel.daysOfWeek([]);
        self.addLessonCardModel.times([]);

        $("td.selected").removeClass("selected");
    }
    // ######################### End private methods ###############################
     
    // ######################### Subscribe methods #################################
    self.currentFaculty.subscribe(function (newValue) {
        LoadGroups();
        self.applySchedule([]);
    });

    self.currentCourse.subscribe(function (newValue) {
        LoadGroups();
        self.applySchedule([]);
    });   

    self.currentGroup.subscribe(function(newValue) {
        self.loadData({
            address: "schedule/getforgroup",
            params: {'groupId': self.currentGroup()},
            onsuccess: function (data) {
                self.applySchedule(data);

                unselectSchedule();
            },
            onerror: function (x,h,r) {
            }
        });
    });

    self.addLessonCardModel.lecturer.subscribe(function(newValue) {
        if(newValue !== undefined) {
            if(newValue.length > 2) {
                self.loadData({
                    address: "lecturer/get",
                    params: {
                        value: newValue
                    },
                    onsuccess: function(data) {
                        $('.typeahead').autocomplete({
                            minLength: 3,
                            source: data
                        });
                    }
                });
            }
        }
    });

    self.addLessonCardModel.time.subscribe(function (newValue) {
        if(newValue === undefined) {
            unselectSchedule();
        }
    });

    self.addLessonCardModel.times.subscribe(function (newValue) {
        if(newValue === undefined) {
            unselectSchedule();
        }
    });

    self.addLessonCardModel.daysOfWeek.subscribe(function (newValue) {
        if(newValue === undefined) {
            unselectSchedule();
        }
    });
    // ######################### End Subscribe methods #############################

    // ######################### ViewModel command #################################
    self.selectFaculty = function(s, e) {
        self.currentFaculty(s.Id);

        $("left-menu>li.active").removeClass("active");
        $("#faculty" + s.Id).addClass("active");

        unselectSchedule();
    };

    self.selectCourse = function(s, e) {
        self.currentCourse(s.Id);

        $("course-list>li.active").removeClass("active");
        $("#course" + s.Id).addClass("active");

        unselectSchedule();
    };

    // show add new lesson window
    self.addLessonView= function () {
        var modal = $('#addLessonCard').modal();
        self.addLessonCardModel.isupdate = false;
        self.addLessonCardModel.window = modal;

        modal.on('hidden', function () {
            self.addLessonCardModel.init();
        });
    };

    // show edit lesson window
    self.editLessonView = function (s, e) {
        if(self.selectedScheduleCard() !== undefined) {
            var modal = $('#editLessonCard').modal();

            self.loadData({
                address: "schedule/getbyid",
                params: {'id': self.selectedScheduleCard()},
                onsuccess: function (data) {
                    self.addLessonCardModel.tutorial(data.Tutorial.Id);
                    self.addLessonCardModel.tutorialType(data.TutorialType.Id);
                    self.addLessonCardModel.auditorium(data.Auditorium.Number);
                    self.addLessonCardModel.lecturer(data.Lecturer.Lastname + " " + data.Lecturer.Firstname + " " + data.Lecturer.Middlename);
                    self.addLessonCardModel.isupdate = true;
                },
                onerror: function (x,h,r) {
                }
            });

            self.addLessonCardModel.window = modal;     
            modal.on('hidden', function () {
                self.addLessonCardModel.init();
            });
        }
    };

    // show delete lesson window
    self.deleteLessonView = function (s, e) {
        if(self.selectedScheduleCard() !== undefined) {
            self.sendData({
                address: "schedule/delete",
                params: {'id': self.selectedScheduleCard()},
                onsuccess: function () {
                    self.loadData({
                        address: "schedule/get",
                        params: {'groupId': self.currentGroup()},
                        onsuccess: function (data) {
                            self.applySchedule(data);
                        },
                        onerror: function (x,h,r) {
                        }
                    });
                }
            });
        }
    };

    self.scheduleTicketClick = function (s, e) {
        var currentTarget = $(e.currentTarget);

        self.selectedScheduleCard(currentTarget.attr("data-scheduleid"));
        
        self.addLessonCardModel.daysOfWeek([currentTarget.attr("data-dayOfWeek")]);
        self.addLessonCardModel.times([s.Id]);
        self.addLessonCardModel.time(s.Id);

        $("td.selected").removeClass("selected");
        currentTarget.addClass("selected");
    };

    self.showDialog = function (s, e) {
        self.deselectAll();

        if(self.selectedScheduleCard() === undefined)
            self.addLessonView();
        else 
            self.editLessonView();
    };

    // Initialize object
    this.init = function () {
        this.prototype.init.call(this);

        //if (!self.hasHash()) getData();

        //$(".content").jScrollPane({ autoReinitialise: true });
//        $(".left-menu").jScrollPane({ 
//            autoReinitialise: true
//        });
        $("a, button, input").tooltip({ placement: 'top' });
        $("select").tooltip({placement: 'top'});  
        
        self.applySchedule([]);
        self.updateWeekDays();
        LoadGroups(); 
    };
}
 
$(function () {
    var schedule = new groupScheduleViewModel(baseViewModel);

    schedule.init();

    ko.applyBindings(schedule);    
})